package com.fnzn.entranceGuard.rest.guard;

import java.io.UnsupportedEncodingException;

/**
 * @author wf_sxf@163.com
 * @date 2018-05-28 8:34
 */
public class ScanUtil {
    /**
     * 伦邦  扫面议
     * START 1 BOARDTYPE 1 ID 2 LENGTH 2 COMMAND 1 DATATYPE 1 DATA 。。。 EO_Check 2 CR 1
     */
    public static  String getData(byte[] all) throws UnsupportedEncodingException {
        int length = all.length;
        if (all.length > 11) {
            byte[] data = new byte[length-11];
            System.arraycopy(all, 8, data, 0, length-11);
            return bytesToUtf8str(data);
        }
        return null;
    }

    /**
     * 获取扫描类型
     * @param all
     * @return
     */
    public static String getDataType(byte[] all) throws UnsupportedEncodingException {
        int length = all.length;
        if (all.length > 8) {
            byte[] data = new byte[1];
            System.arraycopy(all, 7, data, 0, 1);
            return bytesToUtf8str(data);
        }
        return null;
    }

    /**
     * 获取请求类型
     * @param data
     * @return
     */
    public static String getType(byte[] data) throws UnsupportedEncodingException {
        int length = data.length;
        if (data.length > 1) {
            byte[] a = new byte[1];
            System.arraycopy(data, 1, a, 0, 1);
            return bytesToUtf8str(a);
        }
        return null;
    }

    public static String hexTolLetter(String hex) {
        StringBuilder sb = new StringBuilder();
        String[] split = hex.split(",");
        for (String str : split) {
            int i = Integer.parseInt(str, 16);
            sb.append((char)i);
        }
        return sb.toString();
    }

    /**
     * 16进制转字符串
     * @param hex
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String bytesToUtf8str(byte[] hex) throws UnsupportedEncodingException {
        return new String(hex,"UTF-8");
    }
    /**
     * 16进制字符串转byte
     * @param hex
     * @return
     * @throws UnsupportedEncodingException
     */
    public static byte[] Utf8strTobytes(String hex) throws UnsupportedEncodingException {
        String[] data = hex.split(",");
        byte[] b = new byte[data.length];
        for (int r=0;r<data.length;r++){
            b[r] = Integer.valueOf(data[r], 16).byteValue();
        }
        return b;
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        byte[] data = {0x0c,0x40,0x30,0x31,0x30,0x45,0x57,0x33,0x32,0x46,0x39,0x46,0x44,0x31,0x37,0x44,0x31,0x43,0x0d};
        String str = getDataType(data);
        System.out.println(str);
        //System.out.println(hexTolLetter(str));
    }


}
